package com.sjz.myfrist;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/***
 *    GSON可以将一段JSON格式的字符串自动映射成一个对象，不需要再手动去编写代码进行解析。
 *    implementation 'com.google.code.gson:gson:2.7'
 */
public class GJSONActivity extends AppCompatActivity  implements View.OnClickListener{

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gjson_activity);
        Button sendRequest = (Button) findViewById(R.id.send_gjson_request);
        responseText = (TextView) findViewById(R.id.response_gjson_text);
        sendRequest.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_gjson_request) {
            sendRequestWithOkHttp();
        }
    }
    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://192.168.1.13:18888/get_data.json")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithGSON(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void parseJSONWithGSON(String jsonData) {
        Gson gson = new Gson();
        List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>() {}.getType());
        for (App app : appList) {
            Log.d("GJSONActivity", "id is " + app.getId());
            Log.d("GJSONActivity", "name is " + app.getName());
            Log.d("GJSONActivity", "version is " + app.getVersion());
        }
    }


}